import re

from django.http import JsonResponse, HttpResponse
from rest_framework import permissions, status
from rest_framework.settings import api_settings
from rest_framework.utils import json
from rest_framework_mongoengine import viewsets
from mongoengine import QuerySet, Q

from authorshow.models.models import StandardResultSetPagination
from authorshow.models.utils import create_coll_id
from policy.models import Policy, AwardGuide, Awards, AwardsDeclaration, WinningNotice, PolicyInterpretion
from policy.serializer import PolicySerializer, ListPolicySerializer, AwardsGuideSerializer, AwardsSerializer, \
    AwardsDeclarationSerializer, WinningNoticeSerializer, PolicyInterpretionSerializer
from policy.utils import select_policy, select_guide, select_awards
from rest_framework.response import Response

def perform_create(self, serializer):
    serializer.save()

def perform_update(self, serializer):
    serializer.save()

def get_success_headers(self, data):
    try:
        return {'Location': str(data[api_settings.URL_FIELD_NAME])}
    except (TypeError, KeyError):
        return {}

class PolicyViewSet(viewsets.ModelViewSet):
    serializer_class = PolicySerializer
    queryset: QuerySet = Policy.objects.all()

    # 用于分页
    pagination_class = StandardResultSetPagination
    # 权限控制
    permission_classes = (
        permissions.IsAuthenticatedOrReadOnly,
    )

    def create(self, request, *args, **kwargs):
        '''create方法的创建用于生成id'''
        data = request.data
        data['id'] = str(create_coll_id(queryset=self.get_queryset()))
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(data=serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    # list方法用于列出搜索内容
    def list(self, request, *args, **kwargs):
        params = request.query_params
        info = params.get(key='info')
        unit = params.get(key='unit')
        province = params.get(key='province')
        data = params.get(key='data')
        if not (info or unit or province or data):
            queryset = self.filter_queryset(self.get_queryset())
            page = self.paginate_queryset(queryset=queryset)
            serializer = ListPolicySerializer(instance=page, many=True)
            return self.get_paginated_response(serializer.data)
        r_result = select_policy(queryset=self.queryset, info=info, unit=unit, province=province, data=data)
        if r_result is None or r_result.count() is 0:
            err_msg = "未查询到结果"
            return Response(data=err_msg, status=status.HTTP_404_NOT_FOUND)
        page = self.paginate_queryset(queryset=r_result)
        # 序列化所有字段
        serializer = ListPolicySerializer(instance=page, many=True)
        return self.get_paginated_response(serializer.data)

class PolicyInterpretionViewSet(viewsets.ModelViewSet):
    serializer_class = PolicyInterpretionSerializer
    queryset: QuerySet = PolicyInterpretion.objects.all()

    # 用于分页
    pagination_class = StandardResultSetPagination
    # 权限控制
    permission_classes = (
        permissions.IsAuthenticatedOrReadOnly,
    )

    def create(self, request, *args, **kwargs):
        '''create方法的创建用于生成id'''
        data = request.data
        data['id'] = str(create_coll_id(queryset=self.get_queryset()))
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(data=serializer.data, status=status.HTTP_201_CREATED, headers=headers)

def search_policy_year(request):
    '''由搜索框的搜索结果显示按年的政策情况,使用select_policy函数'''
    search_all_policy_year = {}
    all_years = []
    search_policy_year = {}
    years = []
    info = request.GET.get('info', None)
    data = request.GET.get('data', None)
    unit = request.GET.get('unit', None)
    province = request.GET.get('province', None)
    queryset = Policy.objects()
    if not (info or data or unit or province):
        '''若没有参数,显示所有按年的获奖情况'''
        for i in queryset:
            str = i.data.replace("年", "/")
            str1 = str.replace("月", "/")
            str2 = str1.replace("日", "/")
            # print(str2)
            all_years.append(str2.split('/')[0])
        for i in all_years:
            if i in search_all_policy_year:
                search_all_policy_year[i] += 1
            else:
                search_all_policy_year[i] = 1
        # return JsonResponse(search_all_policy_year, json_dumps_params={'ensure_ascii': False})
        res = json.dumps(search_all_policy_year, indent=4, ensure_ascii=False)
        return HttpResponse(res, content_type='application/json', charset='utf-8')
    # 获取筛选数据
    result = select_policy(queryset=queryset, unit=unit, info=info, data=data, province=province)
    if result is None or result.count() is 0:
        err_msg = "未查询到结果"
        # return Response(data=err_msg, status=status.HTTP_404_NOT_FOUND)
        return HttpResponse(err_msg)
    for i in result:
        str = i.data.replace("年", "/")
        str1 = str.replace("月", "/")
        str2 = str1.replace("日", "/")
        years.append(str2.split('/')[0])
    for i in years:
        if i in search_policy_year:
            search_policy_year[i] += 1
        else:
            search_policy_year[i] = 1
    # return JsonResponse(search_policy_year, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(search_policy_year, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')


def search_policy_unit(request):
    '''由搜索框的搜索结果显示按发布单位分布的政策情况,使用select_policy函数'''
    search_all_policy_units = {}
    all_units = []
    search_policy_units = {}
    units = []
    info = request.GET.get('info', None)
    data = request.GET.get('data', None)
    unit = request.GET.get('unit', None)
    province = request.GET.get('province', None)
    queryset = Policy.objects()
    if not (info or data or unit or province):
        for i in queryset:
            for j in range(len(i.unit.split(' '))):
                all_units.append(i.unit.split(' ')[j])
        for i in all_units:
            if i in search_all_policy_units:
                search_all_policy_units[i] += 1
            else:
                search_all_policy_units[i] = 1
        # return JsonResponse(search_all_policy_units, json_dumps_params={'ensure_ascii': False})
        res = json.dumps(search_all_policy_units, indent=4, ensure_ascii=False)
        return HttpResponse(res, content_type='application/json', charset='utf-8')
    # 获取筛选数据
    result = select_policy(queryset=queryset, unit=unit, info=info, data=data, province=province)
    if result is None or result.count() is 0:
        err_msg = "未查询到结果"
        # return Response(data=err_msg, status=status.HTTP_404_NOT_FOUND)
        return HttpResponse(err_msg)
    for i in result:
        for j in range(len(i.unit.split(' '))):
            units.append(i.unit.split(' ')[j])
    for k in units:
        if k in search_policy_units:
            search_policy_units[k] += 1
        else:
            search_policy_units[k] = 1
    # return JsonResponse(search_policy_units, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(search_policy_units, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')


def search_policy_province(request):
    '''由搜索框的搜索结果显示按省份分布的政策情况,使用select_policy函数'''
    search_all_policy_province = {}
    all_province = []
    search_policy_province = {}
    provinces = []
    info = request.GET.get('info', None)
    data = request.GET.get('data', None)
    unit = request.GET.get('unit', None)
    province = request.GET.get('province', None)
    queryset = Policy.objects()
    if not (info or data or unit or province):
        for i in queryset:
            all_province.append(i.province)
        for i in all_province:
            if i in search_all_policy_province:
                search_all_policy_province[i] += 1
            else:
                search_all_policy_province[i] = 1
        # return JsonResponse(search_all_policy_province, json_dumps_params={'ensure_ascii': False})
        res = json.dumps(search_all_policy_province, indent=4, ensure_ascii=False)
        return HttpResponse(res, content_type='application/json', charset='utf-8')
    # 获取筛选数据
    result = select_policy(queryset=queryset, unit=unit, info=info, data=data, province=province)
    if result is None or result.count() is 0:
        err_msg = "未查询到结果"
        # return Response(data=err_msg, status=status.HTTP_404_NOT_FOUND)
        return HttpResponse(err_msg)
    for i in result:
        provinces.append(i.province)
    for k in provinces:
        if k in search_policy_province:
            search_policy_province[k] += 1
        else:
            search_policy_province[k] = 1
    # return JsonResponse(search_policy_province, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(search_policy_province, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')

def search_policy_keywords(request):
    '''由搜索框的搜索结果显示按关键词分布的政策情况,使用select_policy函数'''
    search_all_policy_keywords = {}
    all_keywords = []
    search_policy_keywords = {}
    key_words = []
    info = request.GET.get('info', None)
    data = request.GET.get('data', None)
    unit = request.GET.get('unit', None)
    province = request.GET.get('province', None)
    queryset = Policy.objects()
    if not (info or data or unit or province):
        for i in queryset:
            for j in range(len(i.keywords.split(' '))):
                all_keywords.append(i.keywords.split(' ')[j])
        for i in all_keywords:
            if i in search_all_policy_keywords:
                search_all_policy_keywords[i] += 1
            else:
                search_all_policy_keywords[i] = 1
        # return JsonResponse(search_all_policy_keywords, json_dumps_params={'ensure_ascii': False})
        res = json.dumps(search_all_policy_keywords, indent=4, ensure_ascii=False)
        return HttpResponse(res, content_type='application/json', charset='utf-8')
    # 获取筛选数据
    result = select_policy(queryset=queryset, unit=unit, info=info, data=data, province=province)
    if result is None or result.count() is 0:
        err_msg = "未查询到结果"
        # return Response(data=err_msg, status=status.HTTP_404_NOT_FOUND)
        return HttpResponse(err_msg)
    for i in result:
        for j in range(len(i.keywords.split(' '))):
            key_words.append(i.keywords.split(' ')[j])
    for k in key_words:
        if k in search_policy_keywords:
            search_policy_keywords[k] += 1
        else:
            search_policy_keywords[k] = 1
    # return JsonResponse(search_policy_keywords, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(search_policy_keywords, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')

def policy_hotspot(request):
    '''首页政策热点'''
    hotspot = {}

    keywords = []
    for document in Policy.objects():
        # document.keywords.split(' ')
        # aaa.append(document.keywords.split(' '))
        for i in range(len(document.keywords.split(' '))):
            keywords.append(document.keywords.split(' ')[i])

    for i in keywords:
        if i in hotspot:
            hotspot[i] += 1
        else:
            hotspot[i] = 1
    # return JsonResponse(hotspot, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(hotspot, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')

def policy_year(request):
    '''政策按年份进行统计'''
    year_dict = {}
    year = []
    for document in Policy.objects():
        str = document.data.replace("年", "/")
        str1 = str.replace("月", "/")
        str2 = str1.replace("日", "/")
        # print(str2)
        year.append(str2.split('/')[0])
    for i in year:
        if i in year_dict:
            year_dict[i] += 1
        else:
            year_dict[i] = 1
    # return JsonResponse(year_dict, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(year_dict, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')

def ploicy_source(request):
    '''政策对应文件来源统计'''
    source_dict = {}
    sources = []
    for document in Policy.objects():
        sources.append(document.source)
    for i in sources:
        if i in source_dict:
            source_dict[i] += 1
        else:
            source_dict[i] = 1
    # return JsonResponse(source_dict, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(source_dict, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')

class AwardsGuideViewSet(viewsets.ModelViewSet):
    serializer_class = AwardsGuideSerializer
    queryset: QuerySet = AwardGuide.objects.all()

    # 用于分页
    pagination_class = StandardResultSetPagination
    # 权限控制
    permission_classes = (
        permissions.IsAuthenticatedOrReadOnly,
    )

    def create(self, request, *args, **kwargs):
        '''create方法的创建用于自生成d'''
        data = request.data
        data['id'] = str(create_coll_id(queryset=self.get_queryset()))
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(data=serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def list(self, request, *args, **kwargs):
        params = request.query_params
        level = params.get(key='level')
        name = params.get(key='name')
        unit = params.get(key='unit')
        if not (level or name or unit):
            queryset = self.filter_queryset(self.get_queryset())
            page = self.paginate_queryset(queryset=queryset)
            serializer = AwardsGuideSerializer(instance=page, many=True)
            return self.get_paginated_response(serializer.data)
        r_result = select_guide(queryset=self.queryset, level=level, name=name, unit=unit)
        if r_result is None or r_result.count() is 0:
            err_msg = "未查询到结果"
            return Response(data=err_msg, status=status.HTTP_404_NOT_FOUND)
        page = self.paginate_queryset(queryset=r_result)
        # 序列化所有字段
        serializer = AwardsGuideSerializer(instance=page, many=True)
        return self.get_paginated_response(serializer.data)

class AwardsViewSet(viewsets.ModelViewSet):
    serializer_class = AwardsSerializer
    queryset: QuerySet = Awards.objects.all()

    # 用于分页
    pagination_class = StandardResultSetPagination
    # 权限控制
    permission_classes = (
        permissions.IsAuthenticatedOrReadOnly,
    )

    def create(self, request, *args, **kwargs):
        '''create方法的创建用于自生成id'''
        data = request.data
        data['id'] = str(create_coll_id(queryset=self.get_queryset()))
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(data=serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def list(self, request, *args, **kwargs):
        params = request.query_params
        awards = params.get(key='awards')
        topical = params.get(key='topical')
        #unit = params.get(key='unit')
        # recommendUnit = params.get(key='recommendUnit')
        if not (awards or topical):
            queryset = self.filter_queryset(self.get_queryset())
            page = self.paginate_queryset(queryset=queryset)
            serializer = AwardsSerializer(instance=page, many=True)
            return self.get_paginated_response(serializer.data)
        r_result = select_awards(queryset=self.queryset, awards=awards, topical=topical)
        if r_result is None or r_result.count() is 0:
            err_msg = "未查询到结果"
            return Response(data=err_msg, status=status.HTTP_404_NOT_FOUND)
        page = self.paginate_queryset(queryset=r_result)
        # 序列化所有字段
        serializer = AwardsSerializer(instance=page, many=True)
        return self.get_paginated_response(serializer.data)

def awards_year(request):
    '''由搜索框的搜索结果显示按年的获奖情况,使用select_awards函数'''
    '''url：http://localhost:8000/
       url：http://localhost:8000/?unit=格力
       url：http://localhost:8000/?unit=格力&awards=国家科学技术奖 
    '''
    all_awards_year = {}
    all_years = []
    awards_year = {}
    years = []
    # unit = request.GET.get('unit', None)
    awards = request.GET.get('awards', None)
    topical = request.GET.get('topical', None)
    # recommendUnit = request.GET.get('recommendUnit', None)
    queryset = Awards.objects()
    if not (awards or topical):
        '''若没有参数,显示所有按年的获奖情况'''
        for i in queryset:
            all_years.append(i.year)
        for i in all_years:
            if i in all_awards_year:
                all_awards_year[i] += 1
            else:
                all_awards_year[i] = 1
        # return JsonResponse(all_awards_year, json_dumps_params={'ensure_ascii': False})
        res = json.dumps(all_awards_year, indent=4, ensure_ascii=False)
        return HttpResponse(res, content_type='application/json', charset='utf-8')
    # 获取筛选数据
    result = select_awards(queryset=queryset, awards=awards, topical=topical)
    if result is None or result.count() is 0:
        err_msg = "未查询到结果"
        # return Response(data=err_msg, status=status.HTTP_404_NOT_FOUND)
        return HttpResponse(err_msg)
    for i in result:
        years.append(i.year)
    for i in years:
        if i in awards_year:
            awards_year[i] += 1
        else:
            awards_year[i] = 1
    # return JsonResponse(awards_year, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(awards_year, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')

def awards_name(request):
    '''由搜索框的搜索结果显示按奖项名称分布的获奖情况,使用select_awards函数'''
    all_awards_name = {}
    all_name = []
    awards_name = {}
    name = []
    # unit = request.GET.get('unit', None)
    awards = request.GET.get('awards', None)
    topical = request.GET.get('topical', None)
    # recommendUnit = request.GET.get('recommendUnit', None)
    queryset = Awards.objects()
    if not (awards or topical):
        '''若没有参数,显示所有按年的获奖情况'''
        for i in queryset:
            all_name.append(i.awards)
        for i in all_name:
            if i in all_awards_name:
                all_awards_name[i] += 1
            else:
                all_awards_name[i] = 1
        # return JsonResponse(all_awards_name, json_dumps_params={'ensure_ascii': False})
        res = json.dumps(all_awards_name, indent=4, ensure_ascii=False)
        return HttpResponse(res, content_type='application/json', charset='utf-8')
    # 获取筛选数据
    result = select_awards(queryset=queryset, awards=awards, topical=topical)
    if result is None or result.count() is 0:
        err_msg = "未查询到结果"
        # return Response(data=err_msg, status=status.HTTP_404_NOT_FOUND)
        return HttpResponse(err_msg)
    for i in result:
        name.append(i.awards)
    for i in name:
        if i in awards_name:
            awards_name[i] += 1
        else:
            awards_name[i] = 1
    # return JsonResponse(awards_name, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(awards_name, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')

def awards_unit(request):
    '''由搜索框的搜索结果显示按获奖单位分布的获奖情况,使用select_awards函数'''
    all_awards_units = {}
    all_units = []
    awards_units = {}
    units = []
    # unit = request.GET.get('unit', None)
    awards = request.GET.get('awards', None)
    topical = request.GET.get('topical', None)
    # recommendUnit = request.GET.get('recommendUnit', None)
    queryset = Awards.objects()
    if not (awards or topical):
        '''若没有参数,显示所有按年的获奖情况'''
        for i in queryset:
            for j in range(len(i.unit.split('、'))):
                all_units.append(i.unit.split('、')[j])
        for i in all_units:
            if i in all_awards_units:
                all_awards_units[i] += 1
            else:
                all_awards_units[i] = 1
        # return JsonResponse(all_awards_units, json_dumps_params={'ensure_ascii': False})
        res = json.dumps(all_awards_units, indent=4, ensure_ascii=False)
        return HttpResponse(res, content_type='application/json', charset='utf-8')
    # 获取筛选数据
    result = select_awards(queryset=queryset, awards=awards, topical=topical)
    if result is None or result.count() is 0:
        err_msg = "未查询到结果"
        # return Response(data=err_msg, status=status.HTTP_404_NOT_FOUND)
        return HttpResponse(err_msg)
    for i in result:
        for j in range(len(i.unit.split('、'))):
            units.append(i.unit.split('、')[j])
    for k in units:
        if k in awards_units:
            awards_units[k] += 1
        else:
            awards_units[k] = 1
    # return JsonResponse(awards_units, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(awards_units, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')

def awards_recommendunit(request):
    '''由搜索框的搜索结果显示按发布单位分布的获奖情况,使用select_awards函数'''
    all_awards_recunits = {}
    all_recunits = []
    awards_recunits = {}
    recunits = []
    # unit = request.GET.get('unit', None)
    awards = request.GET.get('awards', None)
    topical = request.GET.get('topical', None)
    # recommendUnit = request.GET.get('recommendUnit', None)
    queryset = Awards.objects()
    if not (awards or topical):
        '''若没有参数,显示所有按年的获奖情况'''
        for i in queryset:
            if i.recommendUnit is not None:
                all_recunits.append(i.recommendUnit)
                for i in all_recunits:
                    if i in all_awards_recunits:
                        all_awards_recunits[i] += 1
                    else:
                        all_awards_recunits[i] = 1
        # return JsonResponse(all_awards_recunits, json_dumps_params={'ensure_ascii': False})
        res = json.dumps(all_awards_recunits, indent=4, ensure_ascii=False)
        return HttpResponse(res, content_type='application/json', charset='utf-8')
    # 获取筛选数据
    result = select_awards(queryset=queryset, awards=awards, topical=topical)
    if result is None or result.count() is 0:
        err_msg = "未查询到结果"
        # return Response(data=err_msg, status=status.HTTP_404_NOT_FOUND)
        return HttpResponse(err_msg)
    for i in result:
        if i.recommendUnit is not None:
            recunits.append(i.recommendUnit)
    for k in recunits:
        if k in awards_recunits:
            awards_recunits[k] += 1
        else:
            awards_recunits[k] = 1
    # return JsonResponse(awards_recunits, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(awards_recunits, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')


def awards_topical(request):
    '''由搜索框的搜索结果显示按研究热点分布的获奖情况,使用select_awards函数'''
    all_awards_topical = {}
    all_topical = []
    awards_topical = {}
    topicals = []
    # unit = request.GET.get('unit', None)
    awards = request.GET.get('awards', None)
    topical = request.GET.get('topical', None)
    # recommendUnit = request.GET.get('recommendUnit', None)
    queryset = Awards.objects()
    if not (awards or topical):
        '''若没有参数,显示所有按年的获奖情况'''
        for i in queryset:
            if i.topical is None:
                continue
            else:
                for j in range(len(i.topical.split(' '))):
                    all_topical.append(i.topical.split(' ')[j])
        for i in all_topical:
            if i in all_awards_topical:
                all_awards_topical[i] += 1
            else:
                all_awards_topical[i] = 1
        # return JsonResponse(all_awards_topical, json_dumps_params={'ensure_ascii': False})
        res = json.dumps(all_awards_topical, indent=4, ensure_ascii=False)
        return HttpResponse(res, content_type='application/json', charset='utf-8')
    # 获取筛选数据
    result = select_awards(queryset=queryset, awards=awards, topical=topical)
    if result is None or result.count() is 0:
        err_msg = "未查询到结果"
        # return Response(data=err_msg, status=status.HTTP_404_NOT_FOUND)
        return HttpResponse(err_msg)
    for i in result:
        if i.topical is None:
            continue
        else:
            for j in range(len(i.topical.split(' '))):
                topicals.append(i.topical.split(' ')[j])
    for k in topicals:
        if k in awards_topical:
            awards_topical[k] += 1
        else:
            awards_topical[k] = 1
    # return JsonResponse(awards_topical, json_dumps_params={'ensure_ascii': False})
    res = json.dumps(awards_topical, indent=4, ensure_ascii=False)
    return HttpResponse(res, content_type='application/json', charset='utf-8')

class AwardsDeclarationViewSet(viewsets.ModelViewSet):
    '''奖项申报情况'''
    serializer_class = AwardsDeclarationSerializer
    queryset: QuerySet = AwardsDeclaration.objects.all()

    # 用于分页
    pagination_class = StandardResultSetPagination
    # 权限控制
    permission_classes = (
        permissions.IsAuthenticatedOrReadOnly,
    )

    def create(self, request, *args, **kwargs):
        '''用于生成instance时自动生成id'''
        data = request.data

        data['id'] = str(create_coll_id(queryset=self.get_queryset()))
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(data=serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class WinningNoticeViewSet(viewsets.ModelViewSet):
    '''获奖公告情况'''
    serializer_class = WinningNoticeSerializer
    queryset: QuerySet = WinningNotice.objects.all()

    pagination_class = StandardResultSetPagination

    permission_classes = (
        permissions.IsAuthenticatedOrReadOnly,
    )
    def create(self, request, *args, **kwargs):
        '''用于生成instance时自动生成id'''
        data = request.data

        data['id'] = str(create_coll_id(queryset=self.get_queryset()))
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(data=serializer.data, status=status.HTTP_201_CREATED, headers=headers)

def policy_orderby_data(request):
    '''由搜索框搜索数据按照时间进行排序'''
    info = request.GET.get('info', None)
    unit = request.GET.get('unit', None)
    queryset = Policy.objects()
    if not (info or unit):
        return HttpResponse('请输入关键词/发布单位进行查询。')
    result = queryset
    if info is not None:
        re_keywords = '.*' + info + '.*'
        result = result(Q(title__icontains=info) | Q(keywords=re.compile(re_keywords, re.IGNORECASE)) | Q(introduction__icontains=info))
    if unit is not None:
        result = result.filter(unit__icontains=unit)
    result = result.order_by('-data')      # 对搜索结果根据年份进行降序排列
    # 搜索获得的数据进行序列化
    serializer = ListPolicySerializer(result, many=True)
    return JsonResponse(serializer.data, safe=False, json_dumps_params={'ensure_ascii': False})


def policy_orderby_source(request):
    '''由搜索框数据按照文件来源进行排序'''
    info = request.GET.get('info', None)
    unit = request.GET.get('unit', None)
    queryset = Policy.objects()
    if not (info or unit):
        return HttpResponse('请输入关键词/发布单位进行查询。')
    result = queryset
    if info is not None:
        re_keywords = '.*' + info + '.*'
        result = result(Q(title__icontains=info) | Q(keywords=re.compile(re_keywords, re.IGNORECASE)) | Q(introduction__icontains=info))
    if unit is not None:
        result = result.filter(unit__icontains=unit)
    # result = result.order_by('source')      # 对搜索结果根据年份进行降序排列
    result = result.sort("source")
    # 搜索获得的数据进行序列化
    serializer = PolicySerializer(result, many=True)
    return JsonResponse(serializer.data, safe=False, json_dumps_params={'ensure_ascii': False})


